<!-- 站点管理组件 -->
<template>
  <div>
    <el-card>
      <!-- 面包屑导航区域 -->
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>急救地图</el-breadcrumb-item>
        <el-breadcrumb-item>站点管理</el-breadcrumb-item>
        <!-- 新增按钮区域 -->
        <span class="btn">
          <el-button type="primary" size="medium" @click="addSiteList">新增</el-button>
          <!-- 批量删除按钮 -->
          <el-button type="danger" size="medium" @click="allDeleteBtn()">批量删除</el-button>
        </span>
      </el-breadcrumb>
      <span class="spnBorder"></span>
      <!-- 表单区域 -->
      <div style="margin-left: 30px;">
        <!-- 表单查询区域 -->
        <el-form :inline="true" :model="queryInfo" ref="queryFromRef" class="demo-form-inline">
          <el-row>
            <el-col :span="6.5">
              <el-form-item label="站点名称" prop="stationName">
                <el-input v-model="queryInfo.stationName" placeholder="请输入站点名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6.5">
              <el-form-item label="站点编码" prop="stationCode">
                <el-input v-model="queryInfo.stationCode" placeholder="请输入站点编码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6.5">
              <el-form-item label="行政区" prop="regionName">
                <el-select v-model="queryInfo.regionName" placeholder="请选择行政区域" clearable>
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4.5">
              <el-form-item class="itemBtns">
                <el-button type="primary" @click="searchBtn">查询</el-button>
                <el-button @click="resetBtn">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        v-loading="pictLoading"
        element-loading-text="数据正在加载中..."
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
        <el-table-column prop="stationName" label="站点名称" width="180" align="center"></el-table-column>
        <el-table-column prop="stationCode" label="站点编码" align="center"></el-table-column>
        <el-table-column label="经纬度" align="center" width="220">
          <template slot-scope="scope">
            <span>X: {{scope.row.longitude}}&nbsp;</span>
            <span>Y: {{scope.row.latitude}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="regionName" label="行政区" align="center"></el-table-column>
        <el-table-column label="是否启用" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.state"
              :inactive-value="0"
              :active-value="1"
              class="switchStyle"
              active-text="启用"
              inactive-text="停用"
              @change="isEnable(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button type="primary" plain size="mini" @click="editSiteData(scope.row)">修改</el-button>
            <el-button type="danger" plain size="mini" @click="deleteSiteData(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 新增和修改对话框 -->
    <el-dialog
      :title="flag===true?'新增':'修改'"
      :visible.sync="addSiteDialogVisible"
      width="40%"
      @close="resetDialogVisible"
    >
      <!-- 新增表单区域 -->
      <el-form
        :label-position="labelPosition"
        label-width="120px"
        :model="addSiteData"
        :rules="addSiteFormRules"
        ref="addSiteFormRef"
      >
        <el-form-item label="站点名称" prop="stationName">
          <el-input v-model="addSiteData.stationName" class="inputs" placeholder="请输入站点名称"></el-input>
        </el-form-item>
        <el-form-item label="站点编码" prop="stationCode">
          <el-input v-model="addSiteData.stationCode" class="inputs" placeholder="请输入站点编码"></el-input>
        </el-form-item>
        <el-form-item label="坐标经度" prop="longitude">
          <el-input v-model="addSiteData.longitude" class="inputs"></el-input>
          <img
            @click="getMap"
            src="../../assets/navImg/经纬度-hover.png"
            style="height:30px;width:30px;"
            class="image"
            alt
          />
        </el-form-item>
        <el-form-item label="坐标纬度" prop="latitude">
          <el-input v-model="addSiteData.latitude" class="inputs"></el-input>
        </el-form-item>
        <el-form-item label="站点位置" prop="stationLocation">
          <el-input v-model="addSiteData.stationLocation" class="inputs"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="stationAddress">
          <el-input v-model="addSiteData.stationAddress" class="inputs" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="行政区" prop="regionName">
          <el-select
            v-model="addSiteData.regionName"
            @change="selectRegion($event)"
            placeholder="请选择行政区"
            class="inputs"
          >
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <div class="dialogBot" slot="footer">
        <el-button @click="addSiteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSiteBtn" :disabled="isDisable">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 地图显示 -->
    <div class="amap-page-container maps" @click="mapBtb" v-if="displayMap">
      <el-amap-search-box
        class="search-box"
        :search-option="searchOption"
        :on-search-result="onSearchResult"
      ></el-amap-search-box>
      <el-amap vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo" :events="events">
        <el-amap-marker v-for="(marker,i) in markers" :key="i" :position="marker"></el-amap-marker>
      </el-amap>
      <div class="el-icon-circle-close circleCss" @click="circleBtn"></div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    let self = this
    return {
      // 地图显示
      displayMap: false,
      markers: [],
      zoom: 12,
      // 地图搜索条件
      searchOption: {
        city: '郑州',
        citylimit: true,
      },
      center: [113.62, 34.75],
      address: '', // 站点位置
      lng: 0, // 经度
      lat: 0, // 纬度
      events: {
        click(e) {
          let { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          // 这里通过高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all',
          })
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
          setTimeout(function () {
            self.displayMap = false // 点击地址1s后隐藏地图
          }, 500)
        },
      },
      // 查询条件
      queryInfo: {
        page: 1,
        limit: 10,
        stationName: '',
        stationCode: '',
        regionName: '',
      },
      // 行政区划
      options: [],
      // 列表数据加载时loading
      pictLoading: false,
      // 列表数据
      tableData: [],
      // 数据总条数
      total: 0,
      // 默认设置新增和修改对话框隐藏
      addSiteDialogVisible: false,
      labelPosition: 'right',
      // 新增和修改表单对象
      addSiteData: {
        id: '',
        stationName: '',
        stationCode: '',
        longitude: '', // 经度
        latitude: '', // 纬度
        stationLocation: '',
        stationAddress: '',
        regionName: '',
        regionCode: '',
        state: '', // 当前状态
      },
      // 控制新增或修改对话框标题显示
      flag: true,
      // 批量删除是的ids数组数据
      ids: [],
      // 新增表单检验规则
      addSiteFormRules: {
        stationName: [
          { required: true, message: '请输入站点名称', trigger: 'blur' },
          { min: 0, max: 40, message: '长度在 0 到 40 个字符', trigger: 'blur' },
        ],
        stationCode: [
          { required: true, message: '请输入站点编码', trigger: 'blur' },
          { min: 0, max: 10, message: '长度在 0 到 10 个字符', trigger: 'blur' },
        ],
        longitude: [{ required: true, message: '请输入站点经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入站点纬度', trigger: 'blur' }],
        stationLocation: [{ required: true, message: '请输入站点位置', trigger: 'blur' }],
        regionName: [{ required: true, message: '请选择行政区划', trigger: 'change' }],
      },
      isDisable: false, //表单重复提交
    }
  },
  created() {
    this.getSiteList()
    this.getRegionName()
  },
  methods: {
    addMarker: function () {
      let lng = 121.5 + Math.round(Math.random() * 1000) / 10000
      let lat = 31.197646 + Math.round(Math.random() * 500) / 10000
      this.markers.push([lng, lat])
    },
    onSearchResult(pois) {
      this.markers = []
      let latSum = 0
      let lngSum = 0
      let markersArr = pois.slice(0, 1)
      if (markersArr.length > 0) {
        markersArr.forEach((poi) => {
          let { lng, lat } = poi
          lngSum += lng
          latSum += lat
          this.markers.push([poi.lng, poi.lat])
        })
        let center = {
          lng: lngSum / markersArr.length,
          lat: latSum / markersArr.length,
        }
        this.center = [center.lng, center.lat]
        this.zoom = 15
      }
    },
    // 获取列表数据
    async getSiteList() {
      this.pictLoading = true
      const { data: res } = await this.$http.get('/sys/station/list_page', { params: this.queryInfo })
      console.log(res)
      this.pictLoading = false
      if (res.errorCode !== 200) return this.$message.error('获取数据列表失败！')
      this.tableData = res.data.list
      this.total = res.data.totalCount
    },
    // 监听当前选中的页数
    handleCurrentChange(currentPage) {
      this.queryInfo.page = currentPage
      this.getSiteList()
    },
    // 监听每页显示多少条数据
    handleSizeChange(pageSize) {
      this.queryInfo.limit = pageSize
      this.getSiteList()
    },
    // 监听表格是否启用按钮的变化
    async isEnable(rowData) {
      console.log(rowData)
      this.addSiteData.state = rowData.state
      this.addSiteData.id = rowData.id
      this.addSiteData.stationName = rowData.stationName
      this.addSiteData.stationCode = rowData.stationCode
      this.addSiteData.longitude = rowData.longitude
      this.addSiteData.latitude = rowData.latitude
      this.addSiteData.stationLocation = rowData.stationLocation
      this.addSiteData.stationAddress = rowData.stationAddress
      this.addSiteData.regionName = rowData.regionName
      this.addSiteData.regionCode = rowData.regionCode
      const { data: res } = await this.$http.put('/sys/station/update', this.addSiteData)
      // console.log(res)
      if (res.errorCode !== 200) return this.$message.error('状态修改失败！')
      this.$message.success('状态修改成功！')
      this.getSiteList()
    },
    // 获取行政区划菜单数据
    async getRegionName() {
      const { data: res } = await this.$http.get('/sys/dict/getDict?code=region')
      // console.log(res.data)
      if (res.errorCode !== 200) return this.$message.error('获取行政列表数据失败！')
      this.options = res.data
    },
    // 监听行政区下拉菜单选中项
    selectRegion(id) {
      console.log(id)
      this.options.find((item) => {
        if (item.id === id) {
          this.addSiteData.regionName = item.name
          this.addSiteData.regionCode = item.code
        }
      })
    },
    // 点击新增按钮显示对话框
    addSiteList() {
      this.addSiteDialogVisible = true
      this.flag = true
      this.addSiteData.stationName = ''
      this.addSiteData.stationCode = ''
      this.addSiteData.longitude = ''
      this.addSiteData.latitude = ''
      this.addSiteData.stationLocation = ''
      this.addSiteData.stationAddress = ''
      this.addSiteData.regionName = ''
      this.addSiteData.regionCode = ''
      this.addSiteData.state = ''
    },
    // 点击修改弹出对话框并重显数据
    editSiteData(row) {
      console.log(row)
      this.addSiteDialogVisible = true
      this.flag = false
      this.addSiteData.id = row.id
      this.addSiteData.stationName = row.stationName
      this.addSiteData.stationCode = row.stationCode
      this.addSiteData.longitude = row.longitude
      this.addSiteData.latitude = row.latitude
      this.addSiteData.stationLocation = row.stationLocation
      this.addSiteData.stationAddress = row.stationAddress
      this.addSiteData.regionName = row.regionName
      this.addSiteData.regionCode = row.regionCode
      this.addSiteData.state = row.state
    },
    // 监听对话框关闭事件
    resetDialogVisible() {
      this.$refs.addSiteFormRef.resetFields()
    },
    // 实现新增和修改功能
    addSiteBtn() {
      if (this.flag) {
        // 表单预检验
        this.$refs.addSiteFormRef.validate(async (valid) => {
          // console.log(valid)
          if (!valid) return
          this.isDisable = true
          // 保留经纬度小数点后六位
          this.addSiteData.longitude = parseFloat(this.addSiteData.longitude).toFixed(6)
          this.addSiteData.latitude = parseFloat(this.addSiteData.latitude).toFixed(6)
          const { data: res } = await this.$http.post('/sys/station/save', this.addSiteData)
          // console.log(res)
          this.isDisable = false //执行请求后就不能点击了
          if (res.errorCode !== 200) return this.$message.error(res.message)
          this.$message.success('添加数据成功！')
          this.getSiteList()
          this.addSiteDialogVisible = false
        })
      } else {
        this.$refs.addSiteFormRef.validate(async (valid) => {
          if (!valid) return
          this.isDisable = true
          // 保留经纬度小数点后六位
          this.addSiteData.longitude = parseFloat(this.addSiteData.longitude).toFixed(6)
          this.addSiteData.latitude = parseFloat(this.addSiteData.latitude).toFixed(6)
          const { data: res } = await this.$http.put('/sys/station/update', this.addSiteData)
          // console.log(res.message)
          this.isDisable = false
          if (res.errorCode !== 200) return this.$message.error(res.message)
          this.$message.success('修改数据成功！')
          this.getSiteList()
          this.addSiteDialogVisible = false
        })
      }
    },
    // 实现单个删除功能
    async deleteSiteData(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/sys/station/delete', { data: { ids: id } })
      // console.log(res)
      if (res.errorCode !== 200) return this.$message.error('删除数据失败！')
      this.$message.success('删除数据成功！')

      //此时已经实现删除操作，所以total的值需要减1，Math.ceil是向上取整，保证始终大于等于1
      const totalPage = Math.ceil((this.total - 1) / this.queryInfo.limit)
      //记录当前页码、记住删除最后一条数据时当前码是最后一页
      const pagenum = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page
      //实现跳转
      this.queryInfo.page = pagenum < 1 ? 1 : pagenum
      // console.log(this.queryInfo.page)
      // 重新渲染（后面方法改为你的方法名）
      this.getSiteList()
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      // console.log(val)
      let ids = []
      val.map(function (v) {
        ids.push(v.id)
      })
      this.ids = ids
      // console.log(this.ids.length)
    },
    // 实现批量删除功能
    async allDeleteBtn() {
      console.log(this.ids)
      if (this.ids.length == 0) return this.$message.info('请先勾选要删除的数据！')
      let params = { ids: this.ids }
      const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/sys/station/delete', { data: params })
      if (res.errorCode !== 200) return this.$message.error('删除数据失败！')
      this.$message.success('删除数据成功！')
      // totalPage 表示为删除n条数据除以每页显示的条数后、得出最后一页页数
      const totalPage = Math.ceil((this.total - this.ids.length) / this.queryInfo.limit)
      const pagenum = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page
      //实现跳转
      this.queryInfo.page = pagenum < 1 ? 1 : pagenum
      this.getSiteList()
    },
    // 查询功能
    searchBtn() {
      this.queryInfo.page = 1
      this.queryInfo.limit = 10
      this.getSiteList()
    },
    // 实现重置功能
    resetBtn() {
      this.$refs.queryFromRef.resetFields()
      this.searchBtn()
    },
    // 获取地图位置信息
    mapBtb() {
      setTimeout(() => {
        this.addSiteData.regionName = ''
        this.addSiteData.regionCode = ''
        this.addSiteData.longitude = this.lng
        this.addSiteData.latitude = this.lat
        this.addSiteData.stationLocation = this.address
        // console.log(this.address.substring())
        let regionNameStr = ''
        if (this.address.indexOf('管城回族区') != -1) {
          regionNameStr = this.address.substring(6, 11)
        } else {
          regionNameStr = this.address.substring(6, 9)
        }
        // this.addLabelData.regionName = regionNameStr
        // console.log(regionNameStr)
        this.options.map((item) => {
          if (item.name == regionNameStr) {
            // console.log(item.name)
            this.addSiteData.regionName = item.name
            this.addSiteData.regionCode = item.code
          }
        })
      }, 1000)
    },
    // 控制地图显示
    getMap() {
      this.displayMap = true
    },
    // 控制地图隐藏
    circleBtn() {
      this.displayMap = false
      this.markers = [] // 清除点标记
      this.lng = this.addSiteData.longitude
      this.lat = this.addSiteData.latitude
      this.address = this.addSiteData.stationLocation
    },
  },
}
</script>
<style lang="less" scoped>
.el-card {
  .spnBorder {
    display: block;
    margin: 15px 0;
    width: 100%;
    border-bottom: 1px solid #ccc;
  }
  .el-pagination {
    float: right;
    margin: 10px 20px;
  }
  .allDelete {
    margin-top: 10px;
  }
}
.el-dialog {
  .el-select {
    width: 80%;
  }
  .el-form-item {
    .inputs {
      width: 85%;
    }
    .image {
      position: absolute;
      right: 70px;
      top: 6px;
      display: inline-block;
      margin: 0 20px;
      width: 80px;
      height: 40px;
      vertical-align: middle;
      cursor: pointer;
    }
  }
}
.maps {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 800px;
  height: 500px;
  z-index: 6666;
  .circleCss {
    position: absolute;
    top: 35px;
    right: -10px;
    font-size: 30px;
    cursor: pointer;
    z-index: 8888;
    background-color: #eee;
    border-radius: 50%;
  }
}
.dialogBot {
  text-align: right !important;
  padding-right: 12%;
}
</style>